package com.test.io.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

	private AsynchronousSocketChannel channel;
	
	public ReadCompletionHandler(AsynchronousSocketChannel channel){
		if(this.channel==null)
			this.channel=channel;
		
	}
	
	
	@Override
	public void completed(Integer result, ByteBuffer attachment) {
		// TODO Auto-generated method stub
		System.out.println("read completion handler completed.. ready to write");
		attachment.flip();
		byte[] bytes=new byte[attachment.remaining()];
		attachment.get(bytes);
		try {
			String req=new String(bytes, "utf-8");
			System.out.println("server receive order is :"+req);
			String order="query time order";
			String currentTime=order.equalsIgnoreCase(req)||req.endsWith(order)
					?new Date().toString():"bad order ";
			doWrite(currentTime);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	
	/**
	 * 将处理结果返回客户端
	 * @param response
	 */
	private void doWrite(String response){
		System.out.println("start to write..");
		if(response!=null && response.length()>0){
			byte[] bytes=response.getBytes();
			ByteBuffer buffer=ByteBuffer.allocate(bytes.length);
			buffer.put(bytes);
			buffer.flip();
			this.channel.write(buffer,buffer,new CompletionHandler<Integer, ByteBuffer>() {

				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					// TODO Auto-generated method stub
					System.out.println("write completed..");
					//如果没有发送成功  继续发送
					if(attachment.hasRemaining()){
						System.out.println("attachment has remaining  and write..");
						channel.write(attachment,attachment,this);
					}
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					// TODO Auto-generated method stub
					try {
						channel.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
			});
		}
	}

	@Override
	public void failed(Throwable exc, ByteBuffer attachment) {
		// TODO Auto-generated method stub
		try {
			this.channel.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}
